<template>
	<div>
    <!-- <div class='create_con_box' @click="createCon">
      创建条件
    </div> -->
    <div class="loadingBox" v-show='showLoading'>
      <i class="lodingIcon el-icon-loading" style="color:#409EFF"></i>
    </div>
		<div class="fd-nav">
			<div class="fd-nav-left">
				<div class="fd-nav-back" @click="toReturn"><i class="anticon anticon-left"></i></div>
				<div class="fd-nav-title">{{name}}</div>
			</div>
			<div class="fd-nav-right">
				<button type="button" class="ant-btn button-publish" @click="saveSet" v-show="!showZZ"><span>保存</span></button>
			</div>
		</div>
		<div class="fd-nav-content">
      <!-- section标签，h5新增标签，用来表示独立的通用章节 -->
			<section class="dingflow-design"> 
				<div class="zoom">
          <!-- 大小加号 -->
					<div :class="'zoom-out'+ (nowVal==50?' disabled':'')" @click="zoomSize(1)"></div>
					<span>{{nowVal}}%</span>
					<div :class="'zoom-in'+ (nowVal==300?' disabled':'')" @click="zoomSize(2)"></div>
				</div>
				<div class="box-scale" id="box-scale" :style="'transform: scale('+nowVal/100+'); transform-origin: 50% 0px 0px;'">
          <!-- 主要的节点组件，全局组件 -->
          <div class="startNode">
						<div >开始</div>
            
					</div>
          <div class="line"></div>
          <!-- <div class="zz" v-if='showZZ'></div> -->
					<nodeWrap ></nodeWrap>
					<div class="endNode">
						<div class="end-node-circle">流程结束</div>
					</div>
				</div>
			</section>
		</div>
		<errorDialog 
			:visible.sync="tipVisible"
			:list="tipList"	
		/>
		<!-- <promoterDrawer /> -->
		<!-- <approverDrawer  :directorMaxLevel="directorMaxLevel"/> -->
		<!-- <copyerDrawer /> -->
		<!-- <conditionDrawer /> -->
	</div>
</template>
<script>
import errorDialog from '@/components/dialog/errorDialog'
// import { getWorkFlowData, setWorkFlowData } from '@/plugins/api.js'
import { mapState,mapMutations } from 'vuex'

import { submit1, histryStatus, getProcessDetail, getStatus, createTemplate, getDag, saveDag, getActiveNodes, regular } from "@/plugins/api.js";
export default {
	components: {
		errorDialog
	},
	data() {
		return {
			tipList: [],
			tipVisible: false,
			nowVal: 100,
			processConfig: {},
			nodeConfig: {},
			workFlowDef: {},
			flowPermission: [],
			directorMaxLevel: 0,
      name: this.$route.query.name,
      showLoad: true
      // showZZ:false,
		};
	},
  computed:{
    ...mapState({
      dataList: state => state.dataList,
      overList: state => state.overList,
      OngoingList: state => state.OngoingList,
      showZZ: state => state.showZZ,
      showEdit: state => state.showEdit,
      storeId: state => state.storeId,
      showLoading : state => state.showLoading,
    }),
    dataKey(){
      return this.$route.query.listId? this.$route.query.listId : this.$route.query.key
    }
  },
	created() {
    this.$store.state.showZZ = false;
    this.$store.state.showEdit = false;
		let tempKey = this.$route.query.tempKey
    let editKey = this.$route.query.editKey
    if(tempKey||editKey){
      if(tempKey&&!editKey){
        this.$store.state.showZZ = true;
        this.$store.state.showEdit = false;
      }else if(!tempKey&&editKey){
        this.$store.state.showZZ = false;
        this.$store.state.showEdit = true;
      }
      
      histryStatus({
        "processKey":397,
      }).then((data)=>{
        console.log(data.data,'--------------执行过的------------')
        if(data){
          this.$store.state.overList = data
        }else{
          this.$store.state.overList=[]
        }
        
        getActiveNodes({
          "processKey":397,
        }).then((data)=>{
          console.log(data,'--------------执中的------------')
          
          if(data){
            this.$store.state.OngoingList = data
          }else{
            this.$store.state.OngoingList=[]
          }
          let keyData = ''
          if(tempKey&&!editKey){
            keyData = tempKey;
          }else{
            keyData = editKey;
          }
          getDag({
            key: keyData
          }).then((res)=>{
            this.$store.state.dataList = res.dagData;
            console.log()
          })
        })
      })
      
    }else{
      regular({
        
      }).then((data)=>{
        let obj = [
          {
            "stepId":1,//节点ID
            "flag":"start",// start开始节点  end 结束节点
            "name":"发起人",//节点名称
            "prevStepId":null,//上个节点
            "children": null,
            "type":'initiate',// 发起人
            "isEnd": '0',//是否是线路结束
            "userIdList": [], // 选择的发起人列表
            "checkList": [],  // 配置的审核状态
            "auditType": [], // 审核状态
            "userPermissionSpecific": {
              "examineType" : 1,
              "designatedPerson" :[],
              "designatedRoles": [],
              "designatedDepartments":[],
              "memberIdList":[]
            }// 选择的审核人列表
          }
        ]
        let id = 1
        data.forEach((item,index)=>{
          id++
          item.stepId = id
          item.prevStepId = id-1
          if(index==data.length-1){
            item.isEnd = '1'
          }
          obj.push(item)
        })
        this.$store.state.storeId = obj.length+1;
        this.$store.state.dataList = obj;
      })
      
      
    }
	},
  mounted() {
    // if(this.showZZ){
    //   histryStatus({
    //     "key":"22",
    //     "type":"16"
    //   }).then((data)=>{
    //     console.log(data.data,'--------------执行过的------------')
    //     this.$store.state.overList = data.data
    //     getStatus({
    //       "key":"22",
    //       "type":"16"
    //     }).then((data)=>{
    //       console.log(data.data,'--------------执中的------------')
    //       this.$store.state.OngoingList = data.data
    //       getProcessDetail({"processId":"1650423006645850112","versionId":25}).then((data)=>{
    //         console.log(data.data.metaDate,'---------详情-------------')
    //         this.$store.state.dataList = data.data.metaDate;
    //       })
    //     })
    //   })
    // }else{
    //   let obj = [
    //     {
    //       "stepId":1,//节点ID
    //       "flag":"start",// start开始节点  end 结束节点
    //       "name":"发起人",//节点名称
    //       "prevStepId":null,//上个节点
    //       "children": null,
    //       "type":'initiate',// 发起人
    //       "isEnd": '0',//是否是线路结束
    //       "userIdList": [], // 选择的发起人列表
    //       "checkList": [],  // 配置的审核状态
    //       "auditType": [], // 审核状态
    //       "userPermissionSpecific": {
    //         "examineType" : 1,
    //         "designatedPerson" :[],
    //         "designatedRoles": [],
    //         "designatedDepartments":[]
    //       }// 选择的审核人列表
    //     },
    //     // {
    //     //   "stepId":2,//节点ID
    //     //   "flag":"regular",// start开始节点  end 结束节点
    //     //   "name":"固定节点",//节点名称
    //     //   "prevStepId":1,//上个节点
    //     //   "children": null,
    
    //     //   "type":'regular',// 发起人
    //     //   "isEnd": '1',//是否是线路结束
    //     //   "userIdList": [], // 选择的发起人列表
    //     //   "checkList": [],  // 配置的审核状态
    //     // },
    //   ]
    //   this.$store.state.storeId = obj.length+1;
    //   this.$store.state.dataList = obj;
    // }
    
    

    
    
    
  },
	methods: {
		...mapMutations(['setTableId', 'setIsTried']),
		toReturn() {
			this.$router.go(-1)
		},
    createCon(){ // 创建条件

    },
		reErr({ childNode }) {
			if (childNode) {
				let { type, error, nodeName, conditionNodes } = childNode
				if (type == 1 || type == 2) {
					if (error) {
						this.tipList.push({ name: nodeName, type: ["", "审核人", "抄送人"][type] })
					}
					this.reErr(childNode)
				} else if (type == 3) {
					this.reErr(childNode)
				} else if (type == 4) {
					this.reErr(childNode)
					for (var i = 0; i < conditionNodes.length; i++) {
						if (conditionNodes[i].error) {
							this.tipList.push({ name: conditionNodes[i].nodeName, type: "条件" })
						}
						this.reErr(conditionNodes[i])
					}
				}
			} else {
				childNode = null
			}
		},
		saveSet() {
      this.showLoad = true
      console.log( JSON.stringify(this.dataList))
      // let params = {
      //   "processId": '1650423006645850112',
      //   "versionId":24,
      //   "children": this.dataList
      // }
      // submit1(params).then((data)=>{
      //   if(data.code == 0){
      //     this.$message({
      //       message: '发布成功',
      //       type: 'success'
      //     });
      //   }
        
      // })
      
      this.saveCheck(this.dataList)
      // await this.ss()
      // if(this.showLoad == true)
      let params = {
        templateSpecific: {
          instanceType: "订单"
        },
        nodeDag : {
          nodes : this.dataList
        },
        processMajorKey: {
          processMajorKey: this.dataKey
        },
      }
      if(this.showLoad == true){
        this.$store.state.showLoading = true;
        createTemplate(params).then((data)=>{
          this.$store.state.showLoading = false;
          if(data.key){
            saveDag(data.key,{dagData:this.dataList}).then((data)=>{
              if(data.code==0){
                this.$message({
                  message: '发布成功',
                  type: 'success'
                });
                this.$router.push({
                  name: 'processList'
                });
              }
              
            })
            
          }
          
        })
      }
      
			
      
		},
    saveCheck(list){
      try{
        list.forEach((item) => {
          if(item.children&&item.children.length>0){
            this.saveCheck(item.children)
          }else{
            if((!item.userIdList||item.userIdList.length==0)&&item.type!='regular'){
              this.$message.error(item.name+'未选择相关人员');
              this.showLoad = false
              throw new Error("EndIterative");
            }
          }
        });
      }catch(e){
        if(e.message != "EndIterative") throw e;
      }
    },
    // ss (){
    //   let params = {
    //     templateSpecific: {
    //       instanceType: "订单"
    //     },
    //     nodeDag : {
    //       nodes : this.dataList
    //     }
    //   }
    //   this.$store.state.showLoading = true;
    //   createTemplate(params).then((data)=>{
    //     console.log(data,'----------发布--------------')
    //     this.$store.state.showLoading = false;
    //     if(data.key){
    //       this.$message({
    //         message: '发布成功',
    //         type: 'success'
    //       });
    //     }
        
    //   })
    // },
		zoomSize(type) {
			if (type == 1) {
				if (this.nowVal == 50) return;
				this.nowVal -= 10;
			} else {
				if (this.nowVal == 300) return;
				this.nowVal += 10;
			}
		}
	}
};
</script>
<style>
@import "../css/workflow.css";

.error-modal-list {
	width: 455px;
}
.loadingBox{
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.7);
  z-index: 99999;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  display: flex;
  justify-content: center;
  align-items: center;
}
.lodingIcon{
  font-size: 40px;
}
.zz{
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0);
  z-index: 99999;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}
.endNode{
  width: 60px;
  height: 60px;
  border-radius: 60px;
  background: #c20202;
  font-size: 12px;
  line-height: 60px;
  text-align: center;
  margin: 0 auto;
  color: #fff;
}
.startNode{
  width: 60px;
  height: 60px;
  border-radius: 60px;
  background: #29cc80;
  font-size: 12px;
  line-height: 60px;
  text-align: center;
  margin: 0 auto;
  color: #fff;
}
.line{
  height: 40px;
  width: 1px;
  background: #ccc;
  margin: 0 auto;
}
.create_con_box{
  position: fixed;
  width: 100px;
  height: 40px;
  line-height: 40px;
  right: 0;
  top: 200px;
  border-radius: 40px 0 0 40px;
  background: #3296fa;
  text-align: center;
  z-index: 999;
  font-size: 16px;
  color: #fff;
  cursor: pointer;
}
</style>